package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 会话资源控制器
 */
@RestController
@RequestMapping("sessions")
public class SessionController {

    @Autowired
    IUserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public JSONResult login(@RequestParam String email, @RequestParam String password){
        JSONResult result = new JSONResult();
        try {
            User user = userService.login(email, password);
            //放入session中
            UserContext.setCurrentUser(user);
            //返回用户信息
            result.setResult(user);
       }catch (Exception e){
           e.printStackTrace();
           result.mark(e.getMessage());
       }
        return result;
    }


    @RequestMapping(method = RequestMethod.DELETE)
    public JSONResult logout(){
        UserContext.getSession().invalidate();
        return new JSONResult();
    }
}
